import { useForm } from 'react-hook-form';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import Button from 'src/component/Button';
import Form from 'src/component/Form';
import FormInput from 'src/component/FormInput';
import { Page } from 'src/constant/Page';
import { openSnackbar } from 'src/redux/uiSlice';
import { GoogleVerify } from 'src/service/userService';
import style from './Step3.module.scss';

type TwoStepVerificationForm = {
  code: string
}

const Step3 = () => {
  const methods = useForm<TwoStepVerificationForm>();
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const onSubmit = (data: TwoStepVerificationForm) => {
    const uMail = localStorage.getItem("uMail")
    const token = localStorage.getItem("token")
    const gState = "启用"
    GoogleVerify({
      uMail: uMail,
      gCode: data.code,
      gState: gState,
      token: token,
    })
      .then((res) => {
        if (res.success) {
          navigate(Page.Account);
          dispatch(openSnackbar({ message: '二步骤验证已启用', severity: 'notify' }));
        } else {
          dispatch(openSnackbar({ message: res.message, severity: 'alert' }))
        }
      })
      .catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));
  };

  return (
    <div>
      <div className={style.heading}>启用二步骤验证</div>
      <Form methods={methods} onSubmit={onSubmit} className={style.formBlock}>
        <FormInput
          name="code"
          label="二步骤验证码"
          required
          asterisked
          autoFocus
        />
        <div className={style.submitButton}>
          <Button type="submit">启用</Button>
        </div>
      </Form>
    </div>
  );
};

export default Step3;
